package info.hexin.mvc.handler;

import info.hexin.mvc.annotation.Method;
import info.hexin.mvc.config.UrlMaping;
import info.hexin.mvc.methodtree.MethodInfo;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * request 上下文
 * 
 * @author hexin
 * 
 */
public class RequestContext {

	private HttpServletRequest request;
	private HttpServletResponse response;

	/**
	 * 引入ThreadLocal 主要是想提高性能
	 */
	private ThreadLocal<MethodInfo> methodThreadLocal = new ThreadLocal<MethodInfo>();

	public HttpServletRequest getRequest() {
		return request;
	}

	public RequestContext setRequest(HttpServletRequest request) {
		this.request = request;
		methodThreadLocal.set(UrlMaping.getMethod(request.getRequestURI(), getMethod()));
		return this;
	}

	public RequestContext setResponse(HttpServletResponse response) {
		this.response = response;
		return this;
	}

	public HttpServletResponse getResponse() {
		return response;
	}

	public String getHeader(String headerName) {
		return request.getHeader(headerName);
	}

	public MethodInfo getMethodInfo() {
		return methodThreadLocal.get();
	}

	/**
	 * 应该抽取到工具
	 * 
	 * @return
	 */
	private Method getMethod() {
		String methodString = request.getMethod();
		if ("GET".equalsIgnoreCase(methodString)) {
			return Method.GET;
		} else if ("POST".equalsIgnoreCase(methodString)) {
			return Method.POST;
		} else if ("PUT".equalsIgnoreCase(methodString)) {
			return Method.PUT;
		} else if ("DELETE".equalsIgnoreCase(methodString)) {
			return Method.DELETE;
		} else if ("PATCH".equalsIgnoreCase(methodString)) {
			return Method.PATCH;
		} else if ("HEAD".equalsIgnoreCase(methodString)) {
			return Method.HEAD;
		} else if ("OPTIONS".equalsIgnoreCase(methodString)) {
			return Method.OPTIONS;
		}
		return Method.ALL;
	}
}
